package com.zgg.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(FileUtils.class);

    private static long byteType = 1;
    private static long kbType = 1024;
    private static long mbType = 1024 * 1024;
    private static long gbType = 1024 * 1024 * 1024;

    /**
     * 删除文件夹下的所有文件
     *
     * @param path
     */
    public static void removeFilePath(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (file.isFile() || file.list().length == 0) {
                file.delete();
            } else {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    removeFilePath(files[i].getPath());
                    files[i].delete();
                }
                //如果文件本身就是目录 ，就要删除目录
                if (isExist(file) && file.isDirectory()) {
                    file.delete();
                }
            }
        }
    }

    /**
     * isImgFile <br/>
     * 根据文件全路径判断当前文件是否是图片文件<br/>
     *
     * @param fileFullPath
     * @return
     */
    public static boolean isImgFile(String fileFullPath) {

        if (StringUtils.isEmpty(fileFullPath)) {
            return false;
        }

        if (fileFullPath.endsWith(".jpg") || fileFullPath.endsWith(".gif") || fileFullPath.endsWith(".png") || fileFullPath.endsWith(".jpeg")) {
            return true;
        }

        return false;
    }

    /**
     * 判断一个文件是否存在
     *
     * @param path 文件路径
     * @return 存在返回true，否则返回false
     */
    public static boolean isExist(String path) {
        try {
            if (path != null && path.trim().length() != 0) {
                return new File(path).exists();
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断一个文件是否存在
     *
     * @param file 文件
     * @return 存在返回true，否则返回false
     */
    public static boolean isExist(File file) {
        try {
            if (file != null) {
                return file.exists();
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * <pre>
     * 判断一个绝对路径下，是否有这个文件。如果没有，则会创建完整路径，并且创建这个文件。
     * </pre>
     *
     * @param path 文件的绝对路径
     */
    public static void createFile(String path) {
        File file = new File(path);
        if (!isExist(path)) {
            file.getParentFile().mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 返回文件大小（GB）
     *
     * @param path
     * @return
     */
    public static Long fileLengthByGB(String path) {
        return fileLength(path, gbType);
    }

    /**
     * 返回文件大小（MB）
     *
     * @param path
     * @return
     */
    public static Long fileLengthByMB(String path) {
        return fileLength(path, mbType);
    }

    /**
     * 返回文件大小（KB）
     *
     * @param path
     * @return
     */
    public static Long fileLengthByKB(String path) {
        return fileLength(path, kbType);
    }

    /**
     * 返回文件大小（Byte）
     *
     * @param path
     * @return
     */
    public static Long fileLengthByByte(String path) {
        return fileLength(path, byteType);
    }

    private static Long fileLength(String path, Long type) {
        File file = new File(path);
        if (isExist(path)) {
            return file.length() / type;
        } else {
            return new Long(0);
        }
    }

    /**
     * 获得当前目录下的所有文件
     *
     * @param filePath
     * @return
     */
    public static List<File> getFilePathList(String filePath) {
        File file = new File(filePath);
        List<File> fileList = new ArrayList<>();
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    fileList.add(files[i]);
                }
            }
        }
        if (file.isFile()) {
            fileList.add(file);
        }
        return fileList;
    }

    /**
     * Spring mvc 框架下文件上传
     *
     * @param request
     * @return
     */
    public static List<String> springFileUpload(HttpServletRequest request) {
        return springFileUpload(request, 0);
    }


    /**
     * Spring mvc 框架下文件上传
     *
     * @param request
     * @return
     */
    public static List<String> springFileUpload(HttpServletRequest request, String filepath) {
        long startTime = System.currentTimeMillis();
        logger.info("==============>>>>>  文件上传开始");
        List<String> fileList = new ArrayList<>();

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            List<MultipartFile> multipartFiles = multiRequest.getFiles("fileName");
            for (MultipartFile multipartFile : multipartFiles) {
                if (multipartFile != null) {
                    logger.error("==============>>>>>  正在上传的文件：【" + multipartFile.getOriginalFilename() + "】");
                    String path = filepath + multipartFile.getOriginalFilename();
                    try {
//                        createFile(path);
                        //上传文件到本地
                        if (!FileUtils.isExist(path)) {
                            multipartFile.transferTo(new File(path));
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fileList.add(path);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        double result = (endTime - startTime) / 1000;
        logger.info("==============>>>>>  文件上传花费时间：" + String.valueOf(endTime - startTime) + "MS ," + result + "S.");
        return fileList;
    }

    /**
     * Spring mvc 框架下文件上传
     *
     * @param request
     * @return
     */
    public static List<String> springFileUpload(HttpServletRequest request, int isZip) {
        long startTime = System.currentTimeMillis();
        logger.info("==============>>>>>  文件上传开始");
        List<String> fileList = new ArrayList<>();

        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            List<MultipartFile> multipartFiles = multiRequest.getFiles("fileName");
            for (MultipartFile multipartFile : multipartFiles) {
                if (multipartFile != null) {
                    logger.info("==============>>>>>  正在上传的文件：【" + multipartFile.getOriginalFilename() + "】");
                    String path = PropertyUtils.getProperty("aliyun.properties", "ali.localUrl") + multipartFile.getOriginalFilename();
                    String new_path = PropertyUtils.getProperty("aliyun.properties", "ali.localUrl.temp") + multipartFile.getOriginalFilename();
                    try {
                        createFile(path);
                        //上传文件到本地
                        multipartFile.transferTo(new File(path));
//                        //1:压缩；0：不压缩
//                        if (isZip == 1) {
//                            ImageUtils.zipImage(path, new_path, 0, 0, 0.8f);
//                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fileList.add(new_path);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        double result = (endTime - startTime) / 1000;
        logger.info("==============>>>>>  文件上传花费时间：" + String.valueOf(endTime - startTime) + "MS ," + result + "S.");
        return fileList;
    }
}
